import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Router, navigate, getPathWithNoRootPath } from 'utils/router';
import Loadable from 'utils/loadable';
import * as actions from './actions/index';
import { Modal } from '@teamix/ui';
import { Layout, SideBar, Body, BodyContent } from '@alife/devops-ui';
import exceed from 'utils/apimap';
import SettingsNav from './nav';
import ProMessage from 'components/proTag/message';
import './index.scss';
import intl from '../../../../../../locale';

const RepositoryPermissions = Loadable({
  loader: () => import('./pages/repositoryPermissions'),
});

const GroupPermissions = Loadable({
  loader: () => import('./pages/groupPermissions'),
});

const Admins = Loadable({
  loader: () => import('./pages/admins'),
});

const SecurityNotify = Loadable({
  loader: () => import('./pages/securityNotify'),
});

const Audit = Loadable({
  loader: () => import('./pages/audit'),
});

const Security = Loadable({
  loader: () => import('./pages/security'),
});

const Backup = Loadable({
  loader: () => import('./pages/backup'),
});

const Crypto = Loadable({
  loader: () => import('./pages/crypto'),
});

const RiskManage = Loadable({
  loader: () => import('./pages/risk'),
});

const Customize = Loadable({
  loader: () => import('./pages/customize'),
});

const Webhooks = Loadable({
  loader: () => import('./pages/webhooks'),
});

const PREFIX = 'enterprise-setting';

class Settings extends Component {
  state = {
    planType: '',
  };

  getBilling = () => {
    if (document.visibilityState === 'visible') {
      this.props.getOrgplan();
    }
  };

  componentDidMount() {
    exceed
      .fetch({
        api: 'organization.getOrgplan',
      })
      .then((res) => {
        if (!res) return;
        const { plan_type } = res;
        this.props.updateData({
          planType: plan_type,
        });

        this.setState({
          planType: plan_type,
        });
      });
    this.props.getOrgplan().then((res) => {
      if (!res) return;
      const { plan_type } = res;
      this.props.updateData({
        planType: plan_type,
      });

      this.setState({
        planType: plan_type,
      });
    });
    document.addEventListener('visibilitychange', this.getBilling);

    // FIXME 临时解决企业设置 Modal 中 balloon 的定位问题
    document.body.style.height = '100vh';
  }

  componentWillUnmount() {
    document.removeEventListener('visibilitychange', this.getBilling);
    // window.TB_NAVIGATION_CONFIG && window.TB_NAVIGATION_CONFIG.lockquery.open({ visible: false });

    // FIXME 临时解决企业设置 Modal 中 balloon 的定位问题
    document.body.style.height = null;
  }

  renderProMessage = () => {
    const { planType } = this.state;
    if (planType === 'premiumVersion') return null;
    return (
      <div className="settings-pro-message">
        <Router basepath={'/settings'} primary={false}>
          <ProMessage path="/member_behavior_security" />
          <ProMessage path="/security_notify" />
        </Router>
      </div>
    );
  };

  renderMain = () => {
    return (
      <Router
        basepath={'/settings'}
        primary={false}
        component={BodyContent}
        className="enterprise-setting__main__content"
      >
        <RepositoryPermissions path="/repository_permissions" />
        <GroupPermissions path="/group_permissions" />
        <Admins path="/admins" />
        <SecurityNotify path="/security_notify" />
        <Audit path="/audit" />
        <Security path="/security" />
        <Backup path="/repository_back_up" />
        <Crypto path="/encryption" />
        <RiskManage path="/security_center" activeTab="overview" />
        <RiskManage path="/member_behavior_security" activeTab="behavior" />
        <RiskManage path="/code_content_security" activeTab="report" />
        <Customize path="/customize" />
        <Webhooks path="/organization_web_hook" />
      </Router>
    );
  };

  onClose = () => {
    navigate('/');
  };

  render() {
    const { planType } = this.state;
    const tabTitle = getPathWithNoRootPath(window.location.pathname).split('/');
    const activeKey = tabTitle.slice(1).join('.');

    return (
      <Modal
        onClose={this.onClose}
        onBack={this.onClose}
        hasArrow
        visible
        noBodyPadding
        title={intl.get({
          id: 'code-assets.pages.settings.EnterpriseSettings',
          defaultMessage: '企业设置',
        })}
        className={PREFIX}
      >
        <Layout noPadding>
          <Body>
            <SideBar size="small">
              <SettingsNav activeKey={activeKey} planType={planType} />
            </SideBar>
            {this.renderMain()}
          </Body>
        </Layout>
      </Modal>
    );
  }
}

export default connect(
  (state) => ({
    ...state.organization.settings.admins,
    enterprisePackage: state.organization.settings.settings.enterprisePackage,
  }),

  (dispatch) => bindActionCreators(actions, dispatch),
)(Settings);
